<?php

namespace App\Controller\Admin;

use App\Entity\SarsUser;
use App\Model\SarsUserModel;
use App\Repository\SarsUserRepository;
use App\Setting\SarsUserSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\SarsUser as Entity;

/**
 * @route("/admin/")
 */
class SarsUserController extends BaseController4Admin
{

    /**
     * @route("SarsUser/add",name="SarsUserPreAdd")
     */
    public function add(Request $request)
    {
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new SarsUserSetting($this->getDoctrine());

        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),"");
        $en = $this->toArray($entity);
        foreach ($en as $key=>&$item) {
            if ($item === null) {
                $item = "";
            }
        }
//        $referer = $request->server->getHeaders()["REFERER"]??"";
        if ($isMy = $this->getParamRequired("isMy")) {
            $isMy = 1;
        }else{
            $isMy = 0;
        }
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "en"   => json_encode($en),
            "isAdd"   => true,
            "isMy"   => $isMy,
        );
        return $this->show("Admin/SarsUser/edit.php.twig",$data);
    }
    /**
     * @route("SarsUser/edit/{id}",name="SarsUserPreEdit")
     */
    public function edit(Entity $entity,Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        $setting = new SarsUserSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),"");
        $en = $this->toArray($entity);
        foreach ($en as $key=>&$item) {
            if ($item === null) {
                $item = "";
            }
        }
//        $referer = $request->server->getHeaders()["REFERER"]??"";
        if ($isMy = $this->getParamRequired("isMy")) {
            $isMy = 1;
        }else{
            $isMy = 0;
        }
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "en"   => json_encode($en),
            "isAdd"   => false,
            "isMy"   => $isMy,
        );
        return $this->show("Admin/SarsUser/edit.php.twig",$data);
    }

    /**
     * @route("SarsUser/edit/{id}/do",name="SarsUserDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        $setting = new SarsUserSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];
            return $this->js_out("保存成功",$this->generateUrl("SarsUserLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("SarsUserPreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("SarsUser",name="SarsUserLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
//        $tools["xingbie"]=[
//            ["id"=>"男","name"=>"男"],
//            ["id"=>"女","name"=>"女"],
//        ];
//        $tools["suifangjibie"]=[
//            ["id"=>"一般","name"=>"一般"],
//            ["id"=>"重点","name"=>"重点"],
//        ];
        $tools["createBy"]=[
            ["id"=>"3","name"=>"河口街道"],
            ["id"=>"4","name"=>"六合街道"],
            ["id"=>"5","name"=>"义和镇"],
            ["id"=>"6","name"=>"新户镇"],
            ["id"=>"7","name"=>"孤岛镇"],
            ["id"=>"8","name"=>"开发区"],
        ];
        $tools["gelifangshi"]=[
            ["id"=>"集中隔离","name"=>"集中隔离"],
            ["id"=>"医院留观","name"=>"医院留观"],
            ["id"=>"居家隔离","name"=>"居家隔离"],
        ];
        $tools["likaidiquzhuzhi"]=[
            ["id"=>"湖北","name"=>"湖北"],
            ["id"=>"广东","name"=>"广东"],
            ["id"=>"河南","name"=>"河南"],
            ["id"=>"浙江","name"=>"浙江"],
            ["id"=>"湖南","name"=>"湖南"],
            ["id"=>"安徽","name"=>"安徽"],
            ["id"=>"江西","name"=>"江西"],
            ["id"=>"武汉","name"=>"武汉"],
            ["id"=>"孝感","name"=>"孝感"],
            ["id"=>"黄冈","name"=>"黄冈"],
            ["id"=>"荆州","name"=>"荆州"],
            ["id"=>"随州","name"=>"随州"],
            ["id"=>"鄂州","name"=>"鄂州"],
            ["id"=>"襄阳","name"=>"襄阳"],
            ["id"=>"黄石","name"=>"黄石"],
            ["id"=>"荆门","name"=>"荆门"],
            ["id"=>"宜昌","name"=>"宜昌"],
            ["id"=>"威宁","name"=>"威宁"],
            ["id"=>"十堰","name"=>"十堰"],
        ];


        $conditions["start"]=[
            ["id"=>"集中隔离","name"=>"集中隔离"],
            ["id"=>"医院留观","name"=>"医院留观"],
            ["id"=>"居家隔离","name"=>"居家隔离"],
        ];

        //通用部分
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new SarsUserModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                if ($key == "start") {
                    $params["conditions"][$this->entitySetting->table]["dengjiriqi"]["gt"]=$val;
                }
                if ($key == "end") {
                    $params["conditions"][$this->entitySetting->table]["dengjiriqi"]["lt"]=$val;
                }
                if ($key == "backStart") {
                    $params["conditions"][$this->entitySetting->table]["likairiqi"]["gte"]=$val;
                }
                if ($key == "backend") {
                    $params["conditions"][$this->entitySetting->table]["likairiqi"]["lte"]=$val;
                }

                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");


        if($excel = $this->getParamRequired("cond")){
            $find = $excel["excel"]??0;
            if ($find) {
                //导出获取全部数据
                $lists = $model->getAdminLists($params,0,9999999999999);
                $this->smartFormat($lists["data"]);
                $rowData=[];
                /**@var $user SarsUser*/
                foreach ($lists["data"] as $index=>$user) {
                    $zhenjie = "";
                    switch ($user->getCreateBy()) {
                        case 3:
                            $zhenjie = "河口街道";
                            break;
                        case 4:
                            $zhenjie = "六合街道";
                            break;
                        case 5:
                            $zhenjie = "义和镇";
                            break;
                        case 6:
                            $zhenjie = "新户镇";
                            break;
                        case 7:
                            $zhenjie = "孤岛镇";
                            break;
                        case 8:
                            $zhenjie = "开发区";
                            break;
                        default:

                    }
                    $rowData[] = [
                        $index+1,$zhenjie
                        ,$user->getXingming()
                        ,"=\"{$user->getLianxidianhua()}\""
                        ,"=\"{$user->getShenfenzhenghao()}\""
                        ,$user->getXiangxizhuzhi()??""
                        ,$user->getTiwen()??""
                        ,$user->getBushizhengzhuang()??""
                        ,$user->getLikaidiquzhuzhi()??""
                        ,$user->getLikairiqi()??""
                        ,$user->getYantushifoutingliu()??""
                        ,$user->getWangfanxiangxixingcheng()??""
                        ,$user->getGelifangshi()??""
                        ,$user->getSuifangyuan()??""
                        ,$user->getJiechugeli()??""
                        ,$user->getGeliguancha()??""
                        ,$user->getZhongdiansuifangyuanyin()??""

                        ,$user->getFangwuleixing()??""
                        ,$user->getLaihekoumudi()??""
                        ,$user->getGongzuodanwei()??""
                        ,$user->getTongxingrenyuan()??""
                    ];
                }
                $title=[
                    "序号","镇街","姓名","联系方式（手机号）","身份证号","家庭住址","体温","有无咳嗽、胸闷等不适症状"
                    ,"在外居住地（酒店名称、地址）","回来时间","车次/航班/汽车/自驾","往返行程详细说明","管控措施（居家隔离、集中隔离、医院留观）"
                    ,"随访人员（姓名+联系方式）","脱离潜伏期日期","是否脱离隔离期","备注"
                    ,"是否有健康卡","风险等级","单位和职务","是否报批","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
                ];
                return $this->excelOut($title,$rowData,date($this->YMDHIS));
            }
        }
        //不导出获取分页数据
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("SarsUserTools"),
            "addUrl"=>$this->generateUrl("SarsUserPreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        $config = $this->entitySetting->formConfig();
        $data = array(
            'title'     => "$entityCnName 列表",
            "tools"     => $tools,
            'urls'      => $urls,
            'isMy'      => 0,
            "config"    => $config,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("SarsUserLists"),$total,$per_page),
        );
        return $this->show("Admin/SarsUser/list.php.twig",$data);
    }

    /**
     * @route("SarsUser/tools",name="SarsUserTools")
     */
    public function tools(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out("参数丢失1",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out("参数丢失2",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    if (property_exists($this->entitySetting,"noDelete")) {

                        if (in_array(0,$this->entitySetting->noDelete)) {
                            continue;
                        }
                        if (in_array($id,$this->entitySetting->noDelete)) {
                            continue;
                        }
                    }
                    $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$id);
                    $em->remove($entity);
                }
                $em->flush();
            }
        }
        //如果是修改操作执行修改操作
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->entitySetting->editKeys ) ) { continue; }
                    $func = "set$key";
                    $func = str_replace("_","",$func);
                    $entity->$func($val);
                }
                $em->persist($entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        $isMy = $cond["cond"]["isMy"]??0;
        if ($isMy) {
            return $this->redirect($this->generateUrl($this->entitySetting->entityName."ListsMy")."?".$queryStr);
        }else{
            return $this->redirect($this->generateUrl($this->entitySetting->entityName."Lists")."?".$queryStr);
        }

    }


    //新增列表选项

    /**
     * @route("SarsUser/my",name="SarsUserListsMy")
     */
    public function listsMy(SarsUserSetting $setting)
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
        //通用部分
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $setting->perPage;
        $model = new SarsUserModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$setting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$setting->table);
        $params["groupBy"][$table]=array("id");
        $params["conditions"][$setting->table]["createBy"]["eq"]=$uid;
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        if($excel = $this->getParamRequired("cond")){
            $find = $excel["excel"]??0;
            if ($find) {
                $rowData=[];
                /**@var $user SarsUser*/
                foreach ($lists["data"] as $index=>$user) {
                    $zhenjie = "";
                    switch ($user->getCreateBy()) {
                        case 3:
                            $zhenjie = "河口街道";
                            break;
                        case 4:
                            $zhenjie = "六合街道";
                            break;
                        case 5:
                            $zhenjie = "义和镇";
                            break;
                        case 6:
                            $zhenjie = "新户镇";
                            break;
                        case 7:
                            $zhenjie = "孤岛镇";
                            break;
                        case 8:
                            $zhenjie = "开发区";
                            break;
                        default:

                    }
                    $rowData[] = [
                        $index+1,$zhenjie
                        ,$user->getXingming()
                        ,"=\"{$user->getLianxidianhua()}\""
                        ,"=\"{$user->getShenfenzhenghao()}\""
                        ,$user->getXiangxizhuzhi()??""
                        ,$user->getTiwen()??""
                        ,$user->getBushizhengzhuang()??""
                        ,$user->getLikaidiquzhuzhi()??""
                        ,$user->getLikairiqi()??""
                        ,$user->getYantushifoutingliu()??""
                        ,$user->getWangfanxiangxixingcheng()??""
                        ,$user->getGelifangshi()??""
                        ,$user->getSuifangyuan()??""
                        ,$user->getJiechugeli()??""
                        ,$user->getGeliguancha()??""
                        ,$user->getZhongdiansuifangyuanyin()??""

                        ,$user->getFangwuleixing()??""
                        ,$user->getLaihekoumudi()??""
                        ,$user->getGongzuodanwei()??""
                        ,$user->getTongxingrenyuan()??""
                    ];
                }
                $title=[
                    "序号","镇街","姓名","联系方式（手机号）","身份证号","家庭住址","体温","有无咳嗽、胸闷等不适症状"
                    ,"在外居住地（酒店名称、地址）","回来时间","车次/航班/汽车/自驾","往返行程详细说明","管控措施（居家隔离、集中隔离、医院留观）"
                    ,"随访人员（姓名+联系方式）","脱离潜伏期日期","是否脱离隔离期","备注"
                    ,"是否有健康卡","风险等级","单位和职务","是否报批","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
                ];
                return $this->excelOut($title,$rowData,date($this->YMDHIS));
            }
        }


        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("SarsUserTools"),
            "addUrl"=>$this->generateUrl("SarsUserPreAdd"),
        );
        $entityCnName = $setting->entityCnName;
        $config = $setting->formConfig();
        $data = array(
            'title'     => "$entityCnName 列表",
            "tools"     => $tools,
            'urls'      => $urls,
            'isMy'      => 1,
            "config"    => $config,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("SarsUserLists"),$total,$per_page),
        );
        return $this->show("Admin/SarsUser/list.php.twig",$data);
    }


    /**
     * @route("SarsUser/info/{id}",name="SarsUserInfo")
     */
    public function SarsUserInfo(SarsUser $user,SarsUserSetting $setting)
    {
        $data["user"] = $user;
        $data["conf"] = $setting->formConfig();

        return $this->show("User/info.php.twig",$data);
    }



    /**
     * @route("SarsUser/add/xls",name="SarsUserPreAddXls")
     */
    public function SarsUserPreAddXls(Request $request)
    {
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new SarsUserSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new SarsUserSetting($this->getDoctrine());

        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formUploadConfig(),"");

        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true
        );
        return $this->show("Admin/SarsUser/upload.php.twig",$data);
    }

    /**
     * @route("SarsUser/add/xls/do",name="SarsUserPreAddXlsDo")
     */
    public function SarsUserPreAddXlsDo(Request $request,SarsUserRepository $repository)
    {
        $uid = $this->needToBeAdmin();
        if(!$file = $this->getParamRequired("file")){return $this->json_out(0,"请上传文件");}


        //通用代码
        $data = $this->excelRead($file["file"]);
//        dd($data);
        $count = 0;
        foreach ($data as $row) {
//            先去重
            $idcode = $row[4];
            if ($findUser = $repository->findOneBy(array("shenfenzhenghao"=>$idcode))) {
//                return $this->json_out(0,"序号{$row[0]},身份证号{$idcode}用户已存在");
            }

            $user = new SarsUser();
            switch ($row[1]) {
                case "河口街道":
                    $user->setCreateBy(3);
                    break;
                case "六合街道":
                    $user->setCreateBy(4);
                    break;
                case "义和镇":
                    $user->setCreateBy(5);
                    break;
                case "新户镇":
                    $user->setCreateBy(6);
                    break;
                case "孤岛镇":
                    $user->setCreateBy(7);
                    break;
                case "开发区":
                    $user->setCreateBy(8);
                    break;
                default:
                    return $this->json_out(0,"序号{$row[0]}资料，镇街解析失败[{$row[1]}]");
            }

//9 => "回来时间"
//14 => "脱离潜伏期日期"
            if (count(myExplodeNumbers($row[9]))<3) {
                $row[9] = "2020.".$row[9];
                $row[9] = str_replace(".","-",$row[9]);
            }else{
                $arr = myExplodeNumbers($row[9]);
                if ($arr[0] == 2020) {
                    $row[9] = "{$arr[0]}-{$arr[1]}-{$arr[2]}";
                }else{
                    $row[9] = "2020-{$arr[1]}-{$arr[2]}";
                }
            }
            $row[9] = date($this->YYMMDD,strtotime($row[9]));

            if (count(myExplodeNumbers($row[14]))<3) {
                $row[14] = "2020.".$row[14];
                $row[14] = str_replace(".","-",$row[14]);
            }
            $row[14] = date($this->YYMMDD,strtotime($row[14]));
            /**@var $user SarsUser */
            $user->setXingming($row[2])
                ->setLianxidianhua($row[3])
                ->setShenfenzhenghao($row[4])
                ->setXiangxizhuzhi($row[5])
                ->setTiwen($row[6])
                ->setBushizhengzhuang($row[7])
                ->setLikaidiquzhuzhi($row[8])
                ->setLikairiqi($row[9])
                ->setYantushifoutingliu($row["10"])
                ->setWangfanxiangxixingcheng($row["11"])
                ->setGelifangshi($row["12"])
                ->setSuifangyuan($row["13"])
                ->setJiechugeli($row["14"])
                ->setZhongdiansuifangyuanyin($row["15"])
                ->setGeliguancha($row["16"])
                ->setDengjiriqi($row["17"])
                ->setFangwuleixing($row[18])//是否有健康卡
                ->setLaihekoumudi($row[19])//风险等级
                ->setGongzuodanwei($row[20])//单位和职务
                ->setTongxingrenyuan($row[21])//是否报批

            ;
            $this->myEm()->persist($user);
            $count++;
        }
        $this->myEm()->flush();
        return $this->json_out(200,"导入{$count}条数据");
    }
//0 => array:17 [
//0 => "序号"
//1 => "镇街"
//2 => "姓名"
//3 => "联系方式（手机号）"
//4 => "身份证号"
//5 => "家庭住址"
//6 => "体温"
//7 => "有无咳嗽、胸闷等不适症状"
//8 => "在外居住地（酒店名称、地址）"
//9 => "回来时间"
//10 => "车次/航班/汽车/自驾"
//11 => "往返行程详细说明"
//12 => "管控措施（居家隔离、集中隔离、医院留观）"
//13 => "随访人员（姓名+联系方式）"
//14 => "脱离潜伏期日期"
//15 => "备注"
//16 => "是否脱离隔离期"
//]
//0 => array:17 [
//0 => 1.0
//1 => "河口街道"
//2 => "葛德华"
//3 => 13589954088.0
//4 => "370503196409060015"
//5 => "秀园4-3-202"
//6 => "无异常"
//7 => "无"
//8 => "河南新乡"
//9 => "01.29"
//10 => "自驾（鲁E555BA）"
//11 => "自驾直接返回河口"
//12 => "居家隔离"
//13 => "王彩霞18562014323张家辉13805465757吴楠18654610858"
//14 => "02.13"
//15 => null
//16 => "已脱离隔离期"
//]
}
